﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FlowerShop.Models;

namespace FlowerShop.DataAccessLayer
{
    public class ProductsDAO
    {
        //Xử lý bảng Products
        private static FlowerDBEntities db = new FlowerDBEntities();
        public static bool InsertProducts(ProductsModels product)
        {
            Product pro = Mapper.productFromModel(product);
            try
            {
                db.AddToProducts(pro);
                db.SaveChanges();
                return true;
            }
            catch(NullReferenceException)
            {
                return false;
            }
        }
        public static bool UpdateProducts(ProductsModels product)
        {
            try
            {
                var pr = db.Products.Single(p => p.ProductID == product.ProductID);
                Product pro = Mapper.productFromModel(product);
                pr.ProductID = pro.ProductID;
                pr.ProductName = pro.ProductName;
                pr.CateID = pro.CateID;
                pr.UnitPrice = pro.UnitPrice;
                pr.Desription = pro.Desription;
                pr.PictureS = pro.PictureS;
                pr.PictureM = pro.PictureM;
                pr.Status = pro.Status;
                db.SaveChanges();
                return true;
            }
            catch(NullReferenceException)
            {
                return false;
            }
        }
        public static bool DeleteProducts(string id)
        {
            try
            {
                Product pr = db.Products.Single(p => p.ProductID == id);
                db.Products.DeleteObject(pr);
                db.SaveChanges();
                return true;
            }
            catch (NullReferenceException)
            {
                return false;
            }
        }
        public static Product SearchProducts(string id)
        {
            var pr = db.Products.Single(p => p.ProductID == id);
            return pr;
        }
        public static List<Product> GetAllProudcts()
        {
            List<Product> pr = (from p in db.Products select p).ToList();
            return pr;
        }
        public static List<Product> GetAllProudctsByCateID(int cateID)
        {
            List<Product> pr = (from p in db.Products
                                where p.CateID==cateID
                                select p).ToList();
            return pr;
        }
    }
}